﻿#include "pch.h"
#include "Client.h"
#include "Server.h"

/**
 * 构造方法。
 * @param server    服务器
 */
Client::Client(Server* server): 
    mBuffer(NULL),
    mDataSize(0),
    mReceived(0),
    mServer(server) {
}

/**
 * 析构方法。
 */
Client::~Client() {
    if (mBuffer != NULL) {
        delete[] mBuffer;
    }

    CSocket::Close();
}

/**
 * 接收到数据的响应方法。
 * @param errorCode 错误码
 */
void Client::OnReceive(int errorCode) {
    // 接收数据长度
    size_t size = 0;
    int read = CSocket::Receive(&size, sizeof(size_t));
    if (read <= 0) {
        CSocket::OnReceive(errorCode);
        return;
    }

    // 接收数据
    char* buffer = new char[size];
    read = CSocket::Receive(buffer, size);
    if (read <= 0) {
        delete[] buffer;
        CSocket::OnReceive(errorCode);
        return;
    }

    // 将数据转换成协议
    GomokuProtocol* pro = (GomokuProtocol*)buffer;

    // 处理协议
    mServer->OnGetMessageFromClient(pro, this);

    // 释放缓存
    delete[] buffer;

    AsyncSelect(FD_READ);
    CSocket::OnReceive(errorCode);
}
